package com.villaday.idf.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.activity.BackHandlerHelper;
import com.villaday.idf.activity.BourbonListActivity;
import com.villaday.idf.activity.FragmentBackHandler;
import com.villaday.idf.activity.HouseDetailsActivityFor3;
import com.villaday.idf.adapter.DynamicListAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.DividerGridItem;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.custom.YiJianTuiGuangDialog;
import com.villaday.idf.model.Collect;
import com.villaday.idf.model.MaterialRecommendEntity;
import com.villaday.idf.model.Material_postersEntity202;
import com.villaday.idf.model.behaviorsEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import byc.imagewatcher.ImageWatcher;
import byc.imagewatcher.MessagePicturesLayout;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * 动态
 */
public class HomeListDynamicFragment extends BaseFragment implements View.OnClickListener, AbsRecyclerViewAdapter.OnItemClickListener, OnAdapterCallbackListener, OkHttpUtil.OnDataListener, SwipeRefreshLayout.OnRefreshListener, ImageWatcher.OnPictureLongPressListener, MessagePicturesLayout.Callback, FragmentBackHandler {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;

    @BindView(R.id.ll)
    LinearLayout ll;


    private DynamicListAdapter dynamicListAdapter;

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();
    private List<MaterialRecommendEntity.BodyEntity.DataListEntity> data = new ArrayList<>();
    private ImageWatcher vImageWatcher;
    private ErrorLayout errorLayout;
    private String tagId;


    public static HomeListDynamicFragment newInstance() {
        HomeListDynamicFragment fragment = new HomeListDynamicFragment();
        return fragment;
    }


    @Override
    protected int getViewResId() {
        return R.layout.fragment_home_dynamic_list;
    }

    @Override
    protected void init(View v) {
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        dynamicListAdapter = new DynamicListAdapter(getContext(), this, this);
        dynamicListAdapter.setPictureClickCallback(this);

        rv.setAdapter(dynamicListAdapter);

        rv.addItemDecoration(new DividerGridItem(getContext()));
        dynamicListAdapter.setOnItemClickListener(this);
        srl.setOnRefreshListener(this);


    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        map.put("tagId", tagId);


        OkHttpUtil.getJSON(getContext(), Constant.URL.material_recommend, map, this);


    }

    public void setTagId(String tagId) {
        this.tagId = tagId;
    }

    @Override
    public void onClick(final View view) {


        switch (view.getId()) {
            case R.id.img_collect: {//收藏
                loadingDialog = LoadingDialog.newInstance("操作中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                /*final behaviors behaviors = new behaviors(data.get((Integer) view.getTag()).isFavorite() ? 107 : 106
                        , new behaviors.ContextEntity(104, data.get((Integer) view.getTag()).getId()));
*/
                Collect collect = new Collect(!data.get((Integer) view.getTag()).isFavorite());
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(getContext(), String.format(Constant.URL.member_collect, "54", data.get((Integer) view.getTag()).getId()), collect, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        dismissLoading();
                        AppContext.isLikeChange = true;

                        LogeUtil.e("member_collect", json);
                        behaviorsEntity behaviorsEntity = gson.fromJson(json, behaviorsEntity.class);

                        if (behaviorsEntity.getBody().getStatus() == 1) {
                            data.get((Integer) view.getTag()).setFavorite(!data.get((Integer) view.getTag()).isFavorite());

                            //dynamicListAdapter.notifyItemChanged((Integer) view.getTag());
                            dynamicListAdapter.notifyDataSetChanged();
                            ToastUtil.initToast(getContext(), data.get((Integer) view.getTag()).isFavorite() ? "收藏成功" : "已取消收藏");

                        } else if (behaviorsEntity.getBody().getStatus() == 0) {
                            ToastUtil.initToast(getContext(), "操作失败");

                        } else {
                            ToastUtil.initToast(getContext(), "操作失败");

                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
            }
            break;
            case R.id.tv_lookShop: {//查看商品
                switch (data.get((Integer) view.getTag()).getProductType()) {
                    case 0: {//无关联产品
                        break;
                    }
                    case 2: {//小区
                        Intent intent = new Intent(getContext(), BourbonListActivity.class);
                        intent.putExtra("villageId", data.get((Integer) view.getTag()).getVillageid());
                        intent.putExtra("city", "");
                        intent.putExtra("area", "");

                        startActivity(intent);
                        break;
                    }
                    case 3: {//房源
                        Intent intent = new Intent(getContext(), HouseDetailsActivityFor3.class);
                        intent.putExtra("type", 0);
                        intent.putExtra("houseId", data.get((Integer) view.getTag()).getHouse().getId());
                        intent.putExtra("presellProduct", false);

                        intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getHouse().getBrokerAge());
                        intent.putExtra("persellId", data.get((Integer) view.getTag()).getPresellId());
                        startActivity(intent);
                        break;
                    }
                    case 52: {//特卖
                        Intent intent = new Intent(getContext(), HouseDetailsActivityFor3.class);
                        intent.putExtra("type", 0);
                        intent.putExtra("houseId", data.get((Integer) view.getTag()).getHouse().getId());
                        intent.putExtra("presellProduct", true);

                        intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getHouse().getBrokerAge());
                        intent.putExtra("persellId", data.get((Integer) view.getTag()).getPresellId());
                        startActivity(intent);
                        break;
                    }
                }


            }
            break;
            case R.id.tv_allFodder0: {//保存图文

               /* Intent intent = new Intent(getContext(), HouseDetailsActivityFor3.class);
                intent.putExtra("type", 1);
                intent.putExtra("houseId", data.get((Integer) view.getTag()).getHouse().getId());
                intent.putExtra("presellProduct", data.get((Integer) view.getTag()).isPresellProduct());

                intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getHouse().getBrokerAge());
                intent.putExtra("persellId", data.get((Integer) view.getTag()).getPresellId());
                startActivity(intent);*/

                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;

                mClipData = ClipData.newPlainText("test", data.get((Integer) view.getTag()).getAdWord());
                mClipboardManager.setPrimaryClip(mClipData);


                if (data.get((Integer) view.getTag()).getEnablePoster() == 0) {//是否调用生成海报接口 0:不生成  1:生成",
                    List<String> picList = new ArrayList<>();
                    if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报

                        picList.add(data.get((Integer) view.getTag()).getPoster());

                    } else {
                        picList.addAll(data.get((Integer) view.getTag()).getPicList());

                    }
                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                    saveImageForRecursive(picList, picList.size(), loadingDialog);
                } else {
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    String materialId = data.get((Integer) view.getTag()).getId();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("modelType", data.get((Integer) view.getTag()).getModelType() + "");
                    OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.material_posters, materialId), hashMap, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            if (!TextUtils.isEmpty(json)) {
                                dismissLoading();
                                final Material_postersEntity202 material_postersEntity = gson.fromJson(json, Material_postersEntity202.class);
                                if ("200".equals(material_postersEntity.getCode())) {
                                    LogeUtil.e("material_postersEntity", json);
                                    List<String> picList = new ArrayList<>();

                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                    }
                                    /*if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {
                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                        } else {
                                            picList.add(data.get((Integer) view.getTag()).getPoster());

                                        }

                                    } else {

                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {

                                            *//*if (data.get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                picList.addAll(data.get((Integer) view.getTag()).getPicList()) ;
                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                }
                                            }else {

                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                    picList.add(data.get((Integer) view.getTag()).getPicList().get(j));
                                                }



                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                }
                                            }*//*

                                            for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                            }

                                        } else {
                                            picList.addAll(data.get((Integer) view.getTag()).getPicList());

                                            if (data.get((Integer) view.getTag()).getPicList().size() < 9) {
                                                for (int j = 0; j < 9 - data.get((Integer) view.getTag()).getPicList().size(); j++) {

                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                }
                                            }


                                        }

                                    }*/
                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                    saveImageForRecursive(picList, picList.size(), loadingDialog);


                                } else {
                                    ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                                }
                            }

                        }

                        @Override
                        public void onFailure(String url, String error) {

                        }
                    });
                }




            }
            break;
            case R.id.tv_allFodder1: {//全部素材

            }
            break;
            case R.id.tv_share0: {//一键发圈

                if (data.get((Integer) view.getTag()).getEnablePoster() == 0) {//是否调用生成海报接口 0:不生成  1:生成",
                    dismissLoading();
                    YiJianTuiGuangDialog yiJianTuiGuangDialog = YiJianTuiGuangDialog.newInstance(data.get((Integer) view.getTag()).getHouse().getBrokerAge());
                    yiJianTuiGuangDialog.show(getActivity().getFragmentManager());
                    yiJianTuiGuangDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                        @Override
                        public void onItemClick(View v) {
                            ClipboardManager mClipboardManager = mClipboardManager =
                                    (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                            ClipData mClipData;

                            mClipData = ClipData.newPlainText("test", data.get((Integer) view.getTag()).getAdWord());
                            mClipboardManager.setPrimaryClip(mClipData);
                            switch (v.getId()) {
                                case R.id.tv_wx: {
                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                    List<String> lists = new ArrayList<String>();
                                    if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                        lists.add(data.get((Integer) view.getTag()).getPoster());


                                    } else {
                                        lists.addAll(data.get((Integer) view.getTag()).getPicList());

                                    }
                                    ShareUtilse.shareImage(getContext(), 0, lists, lists.get(lists.size() - 1),"");
                                }

                                break;
                                case R.id.tv_pyq: {
                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                    List<String> lists = new ArrayList<String>();
                                    if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                        lists.add(data.get((Integer) view.getTag()).getPoster());


                                    } else {
                                        lists.addAll(data.get((Integer) view.getTag()).getPicList());

                                    }
                                    ShareUtilse.shareImage(getContext(), 1, lists, lists.get(lists.size() - 1),"");

                                }
                                break;
                                case R.id.tv_YJTG_save:
                                    List<String> picList = new ArrayList<>();
                                    if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                        picList.add(data.get((Integer) view.getTag()).getPoster());


                                    } else {
                                        picList.addAll(data.get((Integer) view.getTag()).getPicList());

                                    }
                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                    saveImageForRecursive(picList, picList.size(), loadingDialog);

                                    break;
                            }
                        }
                    });
                } else {
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    String materialId = data.get((Integer) view.getTag()).getId();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("modelType", data.get((Integer) view.getTag()).getModelType() + "");
                    OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.material_posters, materialId), hashMap, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            if (!TextUtils.isEmpty(json)) {
                                dismissLoading();
                                final Material_postersEntity202 material_postersEntity = gson.fromJson(json, Material_postersEntity202.class);
                                if ("200".equals(material_postersEntity.getCode())) {
                                    ToastUtil.initToast(getContext(), "分享文案已复制，去粘贴");

                                    YiJianTuiGuangDialog yiJianTuiGuangDialog = YiJianTuiGuangDialog.newInstance(data.get((Integer) view.getTag()).getHouse().getBrokerAge());
                                    yiJianTuiGuangDialog.show(getActivity().getFragmentManager());
                                    yiJianTuiGuangDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View v) {
                                            ClipboardManager mClipboardManager = mClipboardManager =
                                                    (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                                            ClipData mClipData;

                                            mClipData = ClipData.newPlainText("test", data.get((Integer) view.getTag()).getAdWord());
                                            mClipboardManager.setPrimaryClip(mClipData);
                                            switch (v.getId()) {
                                                case R.id.tv_wx: {

                                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                                    List<String> picList = new ArrayList<String>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                   /* if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(data.get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            if (data.get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(data.get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(data.get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }

                                                        } else {
                                                            picList.addAll(data.get((Integer) view.getTag()).getPicList());

                                                            if (data.get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - data.get((Integer) view.getTag()).getPicList().size(); j++) {
                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }
                                                                   // picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    ShareUtilse.shareImage(getContext(), 0, picList, picList.get(picList.size() - 1),"");

                                                }

                                                break;
                                                case R.id.tv_pyq: {
                                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                                    List<String> picList = new ArrayList<String>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                    /*if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(data.get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            if (data.get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(data.get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(data.get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }

                                                        } else {
                                                            picList.addAll(data.get((Integer) view.getTag()).getPicList());

                                                            if (data.get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - data.get((Integer) view.getTag()).getPicList().size(); j++) {
                                                                   // picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());
                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }
                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    ShareUtilse.shareImage(getContext(), 1, picList, picList.get(picList.size() - 1),"");
                                                }
                                                break;
                                                case R.id.tv_YJTG_save:
                                                    List<String> picList = new ArrayList<>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                    /*if (data.get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(data.get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (data.get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            if (data.get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(data.get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(data.get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }

                                                        } else {
                                                            picList.addAll(data.get((Integer) view.getTag()).getPicList());

                                                            if (data.get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - data.get((Integer) view.getTag()).getPicList().size(); j++) {

                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }

                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                                    saveImageForRecursive(picList, picList.size(), loadingDialog);
                                            }
                                        }
                                    });


                                } else {
                                    ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                                }
                            }

                        }

                        @Override
                        public void onFailure(String url, String error) {

                        }
                    });
                }




            }
            break;

            case R.id.tv_share2: {//一键发圈

            }
            break;
        }

    }

    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(getContext(), img.get(0), true);

                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {

                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(getContext(), "图文保存至" + fileName);

            ToastUtil.initToast(getContext(), "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }

    }


    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径


        } catch (Exception e) {
            e.printStackTrace();

            LogeUtil.e("11111111111", e.getMessage());
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    @Override
    public void onItemClick(View v, int position) {

    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (errorLayout != null) {

            errorLayout.setSuccess();
        }
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {

            if (Constant.URL.material_recommend.equals(url)) {
                //  statusLayoutManager.showSuccessLayout();
                LogeUtil.e("material_recommend", json);
                MaterialRecommendEntity materialRecommendEntity = gson.fromJson(json, MaterialRecommendEntity.class);
                removeLoadingItem();
                if (pageNo == 1) {
                    data.clear();
                }
                dismissLoading();
                if ("200".equals(materialRecommendEntity.getCode())) {
                    if (materialRecommendEntity.getBody().getDataList() != null) {
                        boolean isTranslucentStatus = false;

                        data.addAll(materialRecommendEntity.getBody().getDataList());


                        // 一般来讲， ImageWatcher 需要占据全屏的位置
// 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
// 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
//设置指示器（默认小白点）
//设置指示器颜色
// 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
                        vImageWatcher = ImageWatcher.Helper.with(getActivity()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                                .setTranslucentStatus(!isTranslucentStatus ? Utils.calcStatusBarHeight(getContext()) : 0) // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                                .setHintMode(ImageWatcher.POINT)//设置指示器（默认小白点）
                                .setHintColor(getResources().getColor(R.color.colorRed), getResources().getColor(R.color.colorWhite))//设置指示器颜色
                                .setOnPictureLongPressListener(this) // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
                                .setLoader(new ImageWatcher.Loader() {//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
                                    @Override
                                    public void load(Context context, String url, final ImageWatcher.LoadCallback lc) {
                                        Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                                lc.onResourceReady(resource);
                                            }

                                            @Override
                                            public void onLoadStarted(Drawable placeholder) {
                                                lc.onLoadStarted(placeholder);
                                            }

                                            @Override
                                            public void onLoadFailed(Drawable errorDrawable) {
                                                lc.onLoadFailed(errorDrawable);
                                            }
                                        });
                                    }
                                })
                                .create();


                        if (materialRecommendEntity.getBody().isHasNext()) {
                            data.add(new MaterialRecommendEntity.BodyEntity.DataListEntity(1));
                            nextIndex = pageNo + 1;

                        } else {
                            addBaseLine();
                        }
                    } else {
                        addBaseLine();
                    }


                }
                dynamicListAdapter.setData(data);

                if (pageNo == 1&&data.size()>0) {
                    rv.scrollToPosition(0);

                }

            }
        }
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (Constant.URL.material_recommend.equals(url)) {
            if (errorLayout != null) {

                errorLayout.setError(0);
            }
            ToastUtil.initToast(getContext(), "网络错误");

        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new MaterialRecommendEntity.BodyEntity.DataListEntity(2));
        }
    }


    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    @Override
    public boolean onBackPressed() {
        if (vImageWatcher == null) {
            return false;
        } else {
            // 当确认没有子Fragmnt时可以直接return false
            if (!vImageWatcher.handleBackPressed()) {
                return BackHandlerHelper.handleBackPress(this);
            } else {
                return !BackHandlerHelper.handleBackPress(this);
            }
        }


    }

    @Override
    public void onResume() {
        super.onResume();
        if (AppContext.isLikeChange) {
            onRefresh();

            AppContext.isLikeChange = false;
        }
        dismissLoading();

    }

    @Override
    public void onThumbPictureClick(ImageView i, List<ImageView> imageGroupList, List<String> urlList) {
        vImageWatcher.show(i, imageGroupList, urlList);

    }

    public void setErrorLayout(ErrorLayout errorLayout) {

        this.errorLayout = errorLayout;
    }

}
